import api from '@/api';

export default {
  namespace: 'cashCoupon',

  state: {
    cashCouponRules: {
      list: [],
      pagination: {},
    },
    subRules: {
      list: [],
      pagination: {},
    },
    currentSubRule: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(api.cashCoupon.query, payload);
      if (response.errorCode === 0) {
        yield put({
          type: 'saveRules',
          payload: response,
        });
      }
    },

    *fetchCurrentSub({ payload }, { call, put }) {
      const response = yield call(api.cashCoupon.queryCurrentSub, payload);
      if (response.errorCode === 0) {
        yield put({
          type: 'saveCurrentSub',
          payload: response.data,
        });
      }
      return response;
    },

    *fetchSubRule({ payload }, { call, put }) {
      const response = yield call(api.cashCoupon.querySubRules, payload);
      if (response.errorCode === 0) {
        yield put({
          type: 'saveSubRules',
          payload: response,
        });
      }
      return response;
    },
    *fetchCurrentDetail({ payload }, { call, put }) {
      return yield call(api.cashCoupon.queryCurrent, payload);
    },

    *add({ payload }, { call }) {
      return yield call(api.cashCoupon.create, payload);
    },
    *update({ payload }, { call }) {
      return yield call(api.cashCoupon.update, payload);
    },
    *delete({ payload }, { call }) {
      return yield call(api.cashCoupon.delete, payload);
    },
    *addSub({ payload }, { call }) {
      return yield call(api.cashCoupon.subCreate, payload);
    },
    *updateSub({ payload }, { call }) {
      return yield call(api.cashCoupon.subUpdate, payload);
    },
    *deleteSub({ payload }, { call }) {
      return yield call(api.cashCoupon.subDelete, payload);
    },
    *handleEnable({ payload }, { call }) {
      return yield call(api.cashCoupon.enable, payload);
    },
    *handleDisable({ payload }, { call }) {
      return yield call(api.cashCoupon.disable, payload);
    },
  },

  reducers: {
    saveRules(state, action) {
      const { data, pagination } = action.payload;
      return {
        ...state,
        cashCouponRules: {
          list: data,
          pagination,
        },
      };
    },
    saveSubRules(state, action) {
      const { data } = action.payload;
      return {
        ...state,
        subRules: {
          list: data,
        },
      };
    },
    saveCurrentSub(state, { payload }) {
      return {
        ...state,
        currentSubRule: payload,
      };
    },
    clearCurrentSub(state) {
      return {
        ...state,
        currentSubRule: {},
      };
    },
  },
};
